package com.zuorenke.vertx;

import com.zuorenke.help.ReflectionUtils;
import com.zuorenke.help.SortUtils;
import com.zuorenke.vertx.factory.CrosHandlerFactory;
import com.zuorenke.vertx.factory.HandlerFactory;
import com.zuorenke.vertx.handler.*;
import com.zuorenke.vertx.standard.PostHandler;
import com.zuorenke.vertx.standard.PreHandler;
import io.vertx.ext.web.Route;
import io.vertx.ext.web.Router;
import lombok.extern.slf4j.Slf4j;
import org.reflections.Reflections;

import java.util.List;
import java.util.Objects;

/**
 * Router 对象创建
 */
@Slf4j
public class WebRouterInitializer {
	
	// 需要扫描注册的Router路径
	private volatile Reflections reflections;
	
	public WebRouterInitializer(String routerScanAddress) {
		Objects.requireNonNull(routerScanAddress, "The router package address scan is empty.");
		reflections = ReflectionUtils.getReflections(routerScanAddress);
	}
	
	/**
	 * 开始扫描并注册handler
	 */
	public Router initRouter() {
		Router router = RouterUtil.getRouter();
		Route route = router.route();
		// 初始化response
		route.handler(HandlerFactory.builder(ResponseInitPostHandler.class));
		/* 添加跨域的方法 **/
		route.handler(HandlerFactory.builderHandlerByFactory(CrosHandlerFactory.class));
		// 检查handler
		route.handler(HandlerFactory.builder(HeaderCheckHandler.class));
		// 解析body
		route.handler(HandlerFactory.builder(MyBodyHandler.class));
		// 其他前置处理handlers(注解preHandler)
		List<Class<? extends PreHandler>> preHandlers =
				SortUtils.sortOrder(reflections.getSubTypesOf(PreHandler.class), true);
		for(Class clazz : preHandlers){
			route.handler(HandlerFactory.builder(clazz));
		}
//		route.handler(HandlerFactory.builder(RequestServicePreHandler.class));
		// 业务处理(requestMapping)
		route.handler(HandlerFactory.builder(RequestBusinessAsyncHandler.class));
		// 后置处理handlers(注解postHandler)
		List<Class<? extends PostHandler>> postHandlers =
				SortUtils.sortOrder(reflections.getSubTypesOf(PostHandler.class), true);
		for(Class clazz : postHandlers){
			route.handler(HandlerFactory.builder(clazz));
		}
		return router;
	}

}
